import React, { useEffect, useState } from 'react'
import { Modal, Table, Button, Image, Input, message } from 'antd';
import styles from './index.module.css'
//列
import { columns } from '../../constant/faceManagementColumn'

import { getUploadPermit, uploadFileReq } from '../../utils/axiosRequest/api'

import defaultPic from '../../resources/300.png'

//加解密
import { encryptMD5 } from "../../utils/crypt/index"

function FaceManagement() {
    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    const [load, setLoad] = useState(false);
    const [showDataSource, setDataSource] = useState([]);
    const [facePic, setFacePicUrl] = useState();
    const [facePicFile, setFacePicFile] = useState();
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);

    //[]空数组相当于componentDidMount
    useEffect(() => {
        initData()
        return () => {

        }
    }, []);

    function initData() {
        setFacePicUrl(defaultPic)
    }

    function clickUploadFace() {
        setIsModalOpen(true);
    }

    function choosePicture() {
        document.getElementById('fileInput').click();

    }

    function fileSelected() {
        let fileInput = document.getElementById('fileInput');
        let file = fileInput.files[0];
        if (file === undefined) {
            //用户取消选择
            messageApi.open({ type: 'error', content: '取消选择' });
            return
        }
        //图片文件判断
        const validMimeTypes = ['image/png', 'image/jpeg', 'image/jpg'];
        if (!validMimeTypes.includes(file.type)) {
            messageApi.open({ type: 'error', content: '请选择图片文件' });
            return
        }
        //文件大小判断
        const fileSize = file.size//文件大小（字节）
        if (fileSize > 1024 * 1024) {
            messageApi.open({ type: 'error', content: '请选择小于1M的图片' });
            return
        }

        // 创建一个对象URL
        const objectURL = window.URL.createObjectURL(file);
        setFacePicUrl(objectURL)
        setFacePicFile(file)
    }

    //点击上传人脸信息确认按钮
    function handleOk() {
        setConfirmLoading(true)
        //获取文件上传凭证
        const params = new Map()
        const timestamp = Date.now().toString();
        const version = "V3.2.1";
        const actionType = "upload";
        const params1 = "adcvfaa12";
        const params2 = "adcvfaa12";
        const params3 = "ASDA123123";
        const params4 = "asdfasdf!dsafasdf";
        //签名按照顺序
        const signature = timestamp.toLowerCase() + actionType.toLowerCase() + version.toLowerCase() + params3.toLowerCase() + params2.toLowerCase() + params4.toLowerCase() + params1.toLowerCase()

        params.set('timestamp', timestamp);
        params.set('version', version);
        params.set('actionType', actionType);
        params.set('params1', params1);
        params.set('params2', params2);
        params.set('params3', params3);
        params.set('params4', params4);
        params.set('signature', encryptMD5(signature));

        getUploadPermit(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    const permit = data.data.permit;
                    upLoadFile(permit)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    };

    //文件上传
    function upLoadFile(permit) {
        // 可以在这里处理文件，例如读取文件内容或获取文件信息
        const formData = new FormData();
        formData.append('file', facePicFile); // 'file'是你服务器端接收文件的字段名
        const params = new Map()
        params.set('permit', permit)
        params.set('formData', formData)
        uploadFileReq(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    setFacePicUrl(data.data.picUrl)
                    messageApi.open({ type: 'success', content: data.data.des });
                    setIsModalOpen(false);
                    setConfirmLoading(false)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    };

    function handleCancel() {
        setIsModalOpen(false);
    };

    return (
        <div className={styles.root}>
            {contextHolder}
            <Table loading={load} title={() => {
                return (
                    <div className={styles.title} >
                        <Modal confirmLoading={confirmLoading} loading={false} width={'40vw'} title="上传人脸信息"
                            open={isModalOpen} okText="创建" cancelText="取消" onOk={handleOk} onCancel={handleCancel}>
                            <div className={styles.modal_box}>
                                <div className={styles.face_box}>
                                    <input type="file" id="fileInput" style={{ display: 'none' }} onChange={fileSelected} />
                                    <Button onClick={choosePicture} className={styles.select_face} type="primary">选择图片</Button>
                                    <Image
                                        alt='人脸图像'
                                        width={120}
                                        height={120}
                                        placeholder={true}
                                        preview={{ mask: <span>点击预览</span> }}
                                        src={facePic}
                                    /></div>
                                <Input className={styles.inp_box} defaultValue={''} placeholder="请输入用户名..." variant="filled" />
                                <Input className={styles.inp_box} defaultValue={''} placeholder="请输入所属单位..." variant="filled" />
                                <Input className={styles.inp_box} defaultValue={''} placeholder="请输入所属部门..." variant="filled" />
                            </div>
                        </Modal>
                        <Button onClick={clickUploadFace} type="primary">上传人脸信息</Button>
                    </div>
                )
            }} size={'middle'}
                pagination={{ showSizeChanger: false, pageSize: '7', position: ['bottomCenter'], defaultCurrent: '1', total: showDataSource.length }}
                bordered={true} dataSource={showDataSource} columns={columns} scroll={{ x: 100 }} />
        </div>
    )
}

export default FaceManagement;
